<template>
  <a-modal
    :title='title'
    :width='800'
    :visible='visible'
    :confirmLoading='confirmLoading'
    @ok='handleOk'
    @cancel='handleCancel'
    cancelText='关闭'
    wrapClassName='ant-modal-cust-warp'
    style='top:5%;height: 85%;overflow-y: hidden'>

    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='单据编号'>
          <a-input placeholder='请输入单据编号' v-decorator.trim="[ 'billNo', validatorRules.billNo]" />
        </a-form-item>

        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='原有库存'>
          <a-input-number :rows='5' placeholder='原有库存' :disabled="true"
                          v-decorator="[ 'originalSum', validatorRules.originalSum ]" :min='1' :max='100000' />

        </a-form-item>

        <a-form-item
          v-if='isWarehouseIn'
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='入库数量'>
          <a-input-number  :rows='5' placeholder='入库数量' v-decorator="[ 'warehouseInNum', validatorRules.warehouseInNum ]"
                          :min='1' :max='100000' />
        </a-form-item>

        <a-form-item
          v-if='!isWarehouseIn'
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='出库数量'>
          <a-input-number  :rows='5' placeholder='出库数量'
                          v-decorator="[ 'warehouseOutNum', validatorRules.warehouseOutNum ]" :min='1' :max='100000' />
        </a-form-item>

        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='货物走向'>
          <a-textarea :rows='5' placeholder='请输入货物走向' v-decorator="[ 'partFlow',{} ]" />
        </a-form-item>

        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='负责人'>
          <a-input placeholder='请输入负责人' v-decorator.trim="[ 'principalName',{}]" />

        </a-form-item>

        <a-form-item label='上传附件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
        <div>
          <a-upload
            list-type='picture'
            :customRequest='imgAdd'
            :remove='imgDel'
            :multiple='false'
            :file-list='fileList'
            @preview='handlePreview'
            @change='handleChange'>
            <div v-if='fileList.length < 9'>
              <a-button>
                <a-icon type='upload' />
                upload
              </a-button>
            </div>
          </a-upload>
          <a-modal :visible='previewVisible' :footer='null' @cancel='handleCloseImagePreview'>
            <img alt='example' style='width: 100%' :src='previewImage' />
          </a-modal>
        </div>
      </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addWarehouseRecord,  uploadFile } from '@/api/api'

export default {
  name: 'WarehouseModel',
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      isWarehouseIn:true,
      imageUrl: '',
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        originalSum: {
          rules: [
            { required: true, message: '请输入库存数量!' }
          ]
        },
        billNo: {
          rules: [
            { required: false, message: '请输入单据编号!' }
          ]
        },
        warehouseInNum: {
          rules: [
            { required: true, message: '请填写入库数量!' }
          ]
        },
        warehouseOutNum: {
          rules: [
            { required: true, message: '请填写出库数量!' }
          ]
        }
      }
    }
  },
  created() {
  },
  methods: {
    imgAdd(data) {
      let formdata = new FormData()
      formdata.append('file', data.file)
      uploadFile(formdata).then(res => {
        if (res.code === 200) { // 上传成功时（自己封装了response）
          data.onSuccess(res.data)
        } else {
          data.onError()
        }
      })
    },
    // 删除图片
    imgDel(file) {
      this.fileList.splice(this.fileList.indexOf(file), 1)
    },
    // 关闭文件预览模态框
    handleCloseImagePreview() {
      this.previewVisible = false
    },
    // 打开模态框（图片预览）
    async handlePreview(file) {
      console.log(file)
      this.previewImage = file.thumbUrl || file.response.downloadUrl
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.model.originalSum = record.storeSum
      this.visible = true

      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'originalSum', 'billNo', 'warehouseInNum', 'warehouseOutNum'))
      })

    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let motorPartId = that.model.id
          that.confirmLoading = true
          let formData = Object.assign(that.model, values)
          //设置货品id
          delete formData.id
          formData.motorPartId = motorPartId

          //fill attaIds
          formData.attaIds = that.fileList.map(o => {
            return o.id || o.response.id
          }).join(',')


          let obj


          console.log(formData)


          //一直都是新增记录
          obj = addWarehouseRecord(formData)

          obj.then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>